//
//  LEImagePicker.m
//  CreditAddressBook
//
//  Created by Lee on 15/7/28.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "LEImagePicker.h"
#import "CYMeHttpTool.h"
#import "UIInfomationView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImageView+WebCache.h"
#import "CustomIOSAlertView.h"
#import "CYCommon.h"

static LEHandlerBlock _block;

@interface LEImagePicker ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (copy, nonatomic) LEHandlerBlock handler;

@end

@implementation LEImagePicker

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

- (void)showInController:(UIViewController *)controller handler:(LEHandlerBlock)handler; {
    self.handler = handler;
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao1.jpg"]];
     
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, 400);

     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
          [UIInfomationView showActionSheetInView:controller.view WithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"相册",@"相机"] clickAtIndex:^(NSInteger buttonIndex) {
               switch (buttonIndex) {
                    case 2:
                         [CYMeHttpTool imageFromCameraWithController:controller Delegate:self completion:nil];
                         break;
                         
                    case 1:
                         [CYMeHttpTool imageFromPhotoLibraryWithController:controller Delegate:self completion:nil];
                         break;
                         
                    case 0:
                         self.handler = nil;
                         break;
                         
                    default:
                         break;
               }
          }];

     }];
     [alertView show];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        //对图片进行压缩
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        CYLog(@"oldH:%f---oldW:%f", portraitImg.size.height, portraitImg.size.width);
        UIImage *newImage = [UIImage imageWithImage:portraitImg scaledToSize:(CGSize){800, 800}];
        CYLog(@"height---%f, with---%f", newImage.size.height, newImage.size.width);
        if (self.handler) {
            _handler(newImage);
        }
    }];
}

- (void)free {
    self.handler = nil;
}

#pragma mark - 
/**
 *  从相机选取
 *
 *  @param con        <#con description#>
 *  @param completion <#completion description#>
 */
+ (void)imageFromCameraWithController:(UIViewController *)con completion:(LEHandlerBlock)completion {
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        _block = [completion copy];
        
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = [self self];
        [con presentViewController:controller animated:YES completion:nil];
    }
}

/**
 *  从相册选取
 *
 *  @param con
 *  @param completion
 */
+ (void)imageFromPhotoLibraryWithController:(UIViewController *)con completion:(LEHandlerBlock)completion {
    if ([self isPhotoLibraryAvailable]) {
        _block = [completion copy];
        
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = [self self];
        [con presentViewController:controller animated:YES completion:nil];
    }
}

+ (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        //对图片进行压缩
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        CYLog(@"oldH:%f---oldW:%f", portraitImg.size.height, portraitImg.size.width);
        UIImage *newImage = [UIImage imageWithImage:portraitImg scaledToSize:(CGSize){800, 800}];
        CYLog(@"height---%f, with---%f", newImage.size.height, newImage.size.width);
        if (_block) {
            _block(newImage);
        }
    }];
}

+ (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
}

+ (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

+ (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

+ (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

+ (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

@end
